package com.chendx.store.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.customer.pojo.Customer;
import com.chendx.model.customer.pojo.CustomerUser;
import com.chendx.model.user.dto.LoginDto;
import com.chendx.model.user.pojo.User;
import com.chendx.store.user.mapper.CustomerMapper;
import com.chendx.store.user.mapper.CustomerUserMapper;
import com.chendx.store.user.mapper.UserMapper;
import com.chendx.store.user.service.CustomerService;
import com.chendx.store.utils.common.AppJwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by chendx on 2022/4/29.
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper,Customer> implements CustomerService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CustomerUserMapper customerUserMapper;
    @Autowired
    private UserMapper userMapper;

    @Value("${fdfs.url}")
    private String host;
    @Value("${socket.host}")
    private String socketHost;

    @Override
    public ResponseResult loadUserList() {

        /*Customer customer = CustomerThreadLocalUtils.get();
        if (customer == null || StringUtils.isEmpty(customer.getId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_ADMIND);
        }*/
        Customer customer = new Customer();
        customer.setId(1);
        List<CustomerUser> customerUsers = customerUserMapper.selectList(Wrappers.<CustomerUser>lambdaQuery().eq(CustomerUser::getCustomerId, customer.getId()));
        if (customerUsers == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_ADMIND);
        }
        List<Integer> userIds = customerUsers.stream().map(x -> x.getUserId()).collect(Collectors.toList());
        List<User> userList = new ArrayList<>();
        for (Integer userId : userIds){
            User user = userMapper.selectById(userId);
            userList.add(user);
        }
        ResponseResult responseResult = ResponseResult.okResult(userList);
        responseResult.setHost(host);
        responseResult.setSocket(socketHost);
        return responseResult;
    }

    @Override
    public ResponseResult getNoticeCount(String username) {
        Customer customer = new Customer();
        customer.setId(1);
        customer.setUsername("customer");
        String key = "chat:"+customer.getUsername() +"_no_read_notice_count_for_" + username;
        Object o = redisTemplate.boundHashOps(key).get(username);
        Integer count = 0;
        if (o != null){
            count = Integer.valueOf(String.valueOf(o));
        }
        return ResponseResult.okResult(count);
    }

    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验参数
        if (dto.getPhone() == null
                && (StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getPassword()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //用户名密码登录
        if (!StringUtils.isEmpty(dto.getUsername()) && !StringUtils.isEmpty(dto.getPassword())) {
            Customer one = getOne(Wrappers.<Customer>lambdaQuery().eq(Customer::getUsername, dto.getUsername()));
            if (one != null) {
                String pswd = DigestUtils.md5Hex((dto.getPassword() + one.getSalt()).getBytes());
                if (pswd.equals(one.getPassword())) {
                    Map<String, Object> map = new HashMap<>();
                    one.setPassword("");
                    one.setSalt("");
                    map.put("cus", one);
                    map.put("userId", one.getId());
                    map.put("username", one.getUsername());
                    map.put("headpic", one.getHeadpic());
                    map.put("token", AppJwtUtil.getToken(one.getId().longValue()));
                    return ResponseResult.okResult(map);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "客服号不存在");
            }
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
    }
}
